<template>
  <div class="role-manage">
    <!-- 左侧表格区域 -->
    <div class="left-panel">
      <div class="panel-header">
        <h3>角色管理</h3>
        <div class="header-actions">
          <el-button 
            type="info" 
            size="small" 
            icon="el-icon-question"
            @click="showUsageDialog"
          >
            使用提示
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleAddRole"
          >
            增加角色
          </el-button>
          <el-input
            v-model="searchQuery"
            placeholder="搜索"
            prefix-icon="el-icon-search"
            size="small"
            style="width: 200px;"
            @input="handleSearch"
          />
        </div>
      </div>
      
      <div class="table-container">
        <el-table
          :data="paginatedUserRoleList"
          v-loading="loading"
          style="width: 100%"
          :height="'calc(100vh - 120px)'"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="userName" label="姓名" min-width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userPhone" label="手机号" min-width="130">
            <template slot-scope="scope">
              <span>{{ scope.row.userPhone }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称" min-width="120">
            <template slot-scope="scope">
              <el-tag 
                :type="getRoleTagType(scope.row.roleName)"
                size="small"
              >
                {{ scope.row.roleName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" min-width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
                @change="handleStatusChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template slot-scope="scope">
              <div style="display: flex; gap: 8px;">
                <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ totalItems }} 条</span>
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next, jumper"
          :total="totalItems"
          background
        >
        </el-pagination>
      </div>
    </div>

    <!-- 增加/编辑角色对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="roleForm" :rules="formRules" ref="roleForm" label-width="100px">
        <el-form-item label="选择用户" prop="selectedUser">
          <el-select 
            v-model="roleForm.selectedUser" 
            placeholder="请选择用户" 
            style="width: 100%;"
            :disabled="isEdit"
          >
            <el-option
              v-for="user in availableUsers"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            >
              <span style="float: left">{{ user.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ user.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-select 
            v-model="roleForm.roleName" 
            placeholder="请选择角色" 
            style="width: 100%;"
          >
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="普通管理员" value="普通管理员"></el-option>
            <el-option label="普通用户" value="普通用户"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>

    <!-- 使用提示对话框组件 -->
    <RoleUsageDialog 
      :visible.sync="usageDialogVisible"
      @close="handleUsageDialogClose"
      @confirm="handleUsageDialogConfirm"
    />
  </div>
</template>

<script>
import RoleUsageDialog from '@/components/RoleUsageDialog.vue'

export default {
  name: 'RoleManage',
  components: {
    RoleUsageDialog
  },
  data() {
    return {
      loading: false,
      searchQuery: '',
      selectedRows: [],
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      submitting: false,
      editRow: null,
      
      usageDialogVisible: false,
      
      roleForm: {
        selectedUser: '',
        roleName: '',
        status: 1
      },
      
      formRules: {
        selectedUser: [
          { required: true, message: '请选择用户', trigger: 'change' }
        ],
        roleName: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      
      // 角色选项
      roleOptions: [
        { value: '超级管理员', label: '超级管理员' },
        { value: '普通管理员', label: '普通管理员' },
        { value: '普通用户', label: '普通用户' }
      ],
      
      // 员工列表（从员工管理页面获取）
      employeeList: [
        {
          id: 1,
          name: '张三',
          phone: '13800138001',
          password: '123456',
          createTime: '2024-04-15 10:00:00'
        },
        {
          id: 2,
          name: '李四',
          phone: '13800138002',
          password: '123456',
          createTime: '2024-04-16 14:30:00'
        },
        {
          id: 3,
          name: '王五',
          phone: '13800138003',
          password: '123456',
          createTime: '2024-04-17 09:15:00'
        },
        {
          id: 4,
          name: '赵六',
          phone: '13800138004',
          password: '123456',
          createTime: '2024-04-18 11:20:00'
        },
        {
          id: 5,
          name: '钱七',
          phone: '13800138005',
          password: '123456',
          createTime: '2024-04-19 16:45:00'
        },
        {
          id: 6,
          name: '孙八',
          phone: '13800138006',
          password: '123456',
          createTime: '2024-04-20 08:30:00'
        },
        {
          id: 7,
          name: '周九',
          phone: '13800138007',
          password: '123456',
          createTime: '2024-04-21 15:10:00'
        },
        {
          id: 8,
          name: '吴十',
          phone: '13800138008',
          password: '123456',
          createTime: '2024-04-22 12:25:00'
        }
      ],
      
      // 表格数据（显示已分配角色的用户）
        tableData: [
          {
            id: 1,
            userId: 1, // 对应员工ID
            userName: '张三',
            phone: '13800138001',
            roleName: '超级管理员',
            status: 1,
            createTime: '2024-04-15 10:00:00'
          },
          {
            id: 2,
            userId: 2, // 对应员工ID
            userName: '李四',
            phone: '13800138002',
            roleName: '普通管理员',
            status: 1,
            createTime: '2024-04-16 14:30:00'
          },
          {
            id: 3,
            userId: 3, // 对应员工ID
            userName: '王五',
            phone: '13800138003',
            roleName: '普通用户',
            status: 0,
            createTime: '2024-04-17 09:15:00'
          }
        ]
    }
  },
  computed: {
    // 过滤后的表格数据
     filteredTableData() {
       if (!this.searchQuery) {
         return this.tableData
       }
       return this.tableData.filter(item => 
         item.userName.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
         item.phone.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
         item.roleName.toLowerCase().includes(this.searchQuery.toLowerCase())
       )
     },
    
    // 分页后的数据
    paginatedUserRoleList() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredTableData.slice(start, end)
    },
    
    // 总数据量
    totalItems() {
      return this.filteredTableData.length
    },
    
    // 可选择的用户列表（排除已分配角色的用户）
     availableUsers() {
       const assignedUserIds = this.tableData.map(item => item.userId).filter(id => id !== null)
       // 在编辑模式下，需要包含当前编辑的用户
       const excludeIds = this.isEdit && this.editRow 
         ? assignedUserIds.filter(id => id !== this.editRow.userId)
         : assignedUserIds
       return this.employeeList.filter(user => !excludeIds.includes(user.id))
     },
    
    // 获取角色标签类型
    getRoleTagType() {
      return (roleName) => {
        switch (roleName) {
          case '超级管理员':
            return 'danger'
          case '普通管理员':
            return 'warning'
          case '普通用户':
            return 'info'
          default:
            return 'info'
        }
      }
    }
  },
  methods: {
    getPermissionName(permission) {
      const option = this.permissionOptions.find(item => item.value === permission)
      return option ? option.label : permission
    },
    
    handleSearch() {
      this.currentPage = 1
    },
    
    // 重置搜索
    resetSearch() {
      this.searchQuery = ''
      this.currentPage = 1
    },
    
    // 显示使用提示
    showUsageDialog() {
      this.usageDialogVisible = true
    },
    
    // 处理使用提示对话框关闭
    handleUsageDialogClose() {
      this.usageDialogVisible = false
    },
    
    // 处理使用提示对话框确认
    handleUsageDialogConfirm() {
      this.usageDialogVisible = false
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
    },
    
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    handleStatusChange(row) {
      this.$message.success(`角色 "${row.roleName}" 状态已${row.status ? '启用' : '禁用'}`)
    },
    
    handleAddRole() {
      this.dialogTitle = '分配角色'
      this.isEdit = false
      this.dialogVisible = true
      this.resetForm()
    },
    
    handleEdit(row) {
      this.dialogTitle = '编辑用户角色'
      this.isEdit = true
      this.editRow = row
      
      this.roleForm = {
        selectedUser: row.userId,
        roleName: row.roleName,
        status: row.status
      }
      this.dialogVisible = true
    },
    
    handleDelete(row) {
      this.$confirm(`确定要删除用户 "${row.userName}" 的角色分配吗？删除后该用户将失去相应权限。`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.tableData.findIndex(item => item.id === row.id)
        if (index > -1) {
          this.tableData.splice(index, 1)
          this.$message.success('删除成功')
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的用户角色分配')
        return
      }
      
      this.$confirm('确定要删除选中用户的角色分配吗？删除后用户将失去相应权限。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        const selectedIds = this.selectedRows.map(row => row.id)
        this.tableData = this.tableData.filter(item => !selectedIds.includes(item.id))
        this.$message.success('删除成功')
        this.selectedRows = []
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    handleAssignUsers(row) {
      this.currentRole = row
      this.selectedUsers = [...(row.assignedUsers || [])]
      this.setSuperAdmin = row.roleCode === 'SUPER_ADMIN'
      this.assignDialogVisible = true
    },
    
    confirmSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.submitting = true
          
          // 获取选中的用户信息
          const selectedUser = this.employeeList.find(user => user.id === this.roleForm.selectedUser)
          
          if (!selectedUser) {
            this.$message.error('请选择有效的用户')
            this.submitting = false
            return
          }
          
          setTimeout(() => {
            if (this.isEdit) {
              // 编辑用户角色
              const index = this.tableData.findIndex(item => item.id === this.editRow.id)
              if (index > -1) {
                this.tableData.splice(index, 1, {
                   ...this.editRow,
                   userId: selectedUser.id,
                   userName: selectedUser.name,
                   phone: selectedUser.phone,
                   roleName: this.roleForm.roleName,
                   status: this.roleForm.status,
                   updateTime: new Date().toLocaleString('zh-CN', {
                     year: 'numeric',
                     month: '2-digit',
                     day: '2-digit',
                     hour: '2-digit',
                     minute: '2-digit',
                     second: '2-digit'
                   }).replace(/\//g, '-')
                 })
              }
              this.$message.success('编辑成功')
            } else {
              // 新增用户角色
              const newUserRole = {
                 id: Date.now(),
                 userId: selectedUser.id,
                 userName: selectedUser.name,
                 phone: selectedUser.phone,
                 roleName: this.roleForm.roleName,
                 status: this.roleForm.status,
                 createTime: new Date().toLocaleString('zh-CN', {
                   year: 'numeric',
                   month: '2-digit',
                   day: '2-digit',
                   hour: '2-digit',
                   minute: '2-digit',
                   second: '2-digit'
                 }).replace(/\//g, '-')
               }
              this.tableData.unshift(newUserRole)
              this.$message.success('角色分配成功')
            }
            
            this.submitting = false
            this.dialogVisible = false
            this.resetForm()
          }, 1000)
        }
      })
    },
    
    confirmAssign() {
      this.assigning = true
      
      setTimeout(() => {
        const index = this.mockRoleList.findIndex(item => item.id === this.currentRole.id)
        if (index > -1) {
          this.mockRoleList[index].assignedUsers = [...this.selectedUsers]
          
          if (this.setSuperAdmin) {
            // 如果设为超管，更新权限
            this.mockRoleList[index].permissions = this.permissionOptions.map(p => p.value)
            this.mockRoleList[index].roleCode = 'SUPER_ADMIN'
          }
        }
        
        this.assigning = false
        this.assignDialogVisible = false
        this.resetAssignForm()
        this.$message.success('分配成功')
      }, 1000)
    },
    
    resetForm() {
      this.roleForm = {
        selectedUser: '',
        roleName: '',
        status: 1
      }
      this.editRow = null
      if (this.$refs.roleForm) {
        this.$refs.roleForm.resetFields()
      }
    },
    
    resetAssignForm() {
      this.currentRole = {}
      this.selectedUsers = []
      this.setSuperAdmin = false
    },
    
    // 获取用户名显示
    getUserName(userId) {
      const user = this.employeeList.find(emp => emp.id === userId)
      return user ? user.name : ''
    }
  }
}
</script>

<style scoped>
.role-manage {
  height: calc(100vh - 120px);
  padding: 16px;
}

.left-panel {
  width: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-container {
  flex: 1;
  padding: 0 20px;
  overflow: hidden;
  height: calc(100vh - 120px);
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

.table-container .el-table {
  flex: 1 1 auto;
  min-height: 0;
}

.table-container .el-table__body-wrapper {
  max-height: 100%;
  min-height: 200px;
  overflow-y: auto !important;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  border: 1px solid #ebeef5;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.el-checkbox {
  margin-right: 0;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .role-manage {
    padding: 10px;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
}
</style>